package utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //定义一个数据源对象
    private  static DataSource dataSource;
    //定义URL
    private static String url="jdbc:mysql://localhost:3306/java116";
    //定义用户名
    private static String username="root";
    //定义密码
    private static String password="123456";
    //在类加载的时候初始化dataSource对象
    static {
        //定义mysql数据源
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库的连接串
        mysqlDataSource.setURL(url);
        //设置用户名和密码
        mysqlDataSource.setUser(username);
        mysqlDataSource.setPassword(password);
        //定义jdbc数据源对象
       dataSource = mysqlDataSource;
    }
    private DBUtil() {}

    public static Connection getConnection() throws SQLException{
        return  dataSource.getConnection();
    }
    public static void close(ResultSet resultSet, Statement statement, Connection connection){

            // 7关闭资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

